package org.linlinjava.litemall.db.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.DateTimeUtil;
import org.linlinjava.litemall.db.util.LocalDateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 优惠券满额计算使用商品总价，不计税费、运费、其他优惠
 */
@Service
@Slf4j
public class CouponVerifyService {

    @Autowired
    private LitemallGoodsService litemallGoodsService;
    @Autowired
    private LitemallShopRegionService shopRegionService;

    @Autowired
    private LumiereCouponStrategyService lumiereCouponStrategyService;
    @Autowired
    private LumiereCouponUserService lumiereCouponUserService;

    /**
     * 判断新优惠券是否能够使用
     */
    public List<LumiereCouponUser> checkCouponStrategy(List<LumiereCouponUser> lumiereCouponUsers,BigDecimal checkedGoodsPrice,Integer ranges,Integer shopId,List<Integer> gsIds){
        List<LumiereCouponUser> couponUserList = new ArrayList<>();
        for(LumiereCouponUser lumiereCouponUser:lumiereCouponUsers){
            //检测优惠券
            if(LocalDateTime.now().isAfter(lumiereCouponUser.getEndTime())){
                continue;
            }
            if(lumiereCouponUser.getUsedTime()!=null){
                continue;
            }
            LumiereCouponStrategy couponStrategy = lumiereCouponStrategyService.findByid(lumiereCouponUser.getStrategyId());
            //LumiereCoupon coupon = lumiereCouponService.getById(couponStrategy.getCouponId());
            //判断使用范围 使用范围：1APP 2POS 3网站
            if(!Arrays.stream(couponStrategy.getRanges()).anyMatch(i -> i == ranges)){
                continue;
            }
            //查看优惠券策略折扣类型
            if(checkedGoodsPrice.compareTo(couponStrategy.getMin())<0){
                //满减的话要看是否达到满减要求
                continue;
            }
            if((couponStrategy.getCouponType()==1||couponStrategy.getCouponType()==3||couponStrategy.getCouponType()==5)&&couponStrategy.getUseLimit()!=null && couponStrategy.getUseLimit()!=4){
                //判断年月周天的限制
                LocalDateTime[] locaTimeStartEnd = DateTimeUtil.getLocaTimeStartEnd(couponStrategy.getUseLimit().intValue());
                long useCount = lumiereCouponUserService.count(Wrappers.lambdaQuery(LumiereCouponUser.class)
                        .eq(LumiereCouponUser::getUserId, lumiereCouponUser.getUserId())
                        .eq(LumiereCouponUser::getCouponId, lumiereCouponUser.getCouponId())
                        .eq(LumiereCouponUser::getStrategyId, lumiereCouponUser.getStrategyId())
                        .isNotNull(LumiereCouponUser::getUsedTime)
                        .between(LumiereCouponUser::getUsedTime, locaTimeStartEnd[0], locaTimeStartEnd[1]));
                if(couponStrategy.getUseLimitNum()<=useCount){
                    continue;
                }
            }
            //下面写对商品、地区、菜单的限制

            //匹配限制区域
            if (couponStrategy.getAreaLimit() != null && couponStrategy.getAreaLimit() == 1 && shopId != null) {
                if (couponStrategy.getRegions() != null) {

                    Integer[] regionsId = couponStrategy.getRegions();
                    if (regionsId != null && regionsId.length > 0) {
                        List<LitemallShopRegion> shopRegions = shopRegionService.queryByShopIdAndRegionIds(shopId, Arrays.asList(regionsId));
                        if (shopRegions.size() == 0) {
                            continue;
                        }
                    }
                }
            }

            if(gsIds!=null){
                //匹配 指定分类，指定商品优惠券
                Short goodType = couponStrategy.getGoodsType();
                if (goodType.equals(Constants.GOODS_TYPE_CATEGORY)) {
                    Integer[] couponGoodsValue = couponStrategy.getGoodsValue();

                    //通过商品查询分类
                    List<LitemallGoods> gs = litemallGoodsService.findByIds(gsIds);
                    List<Integer> cateIds = gs.stream().map(LitemallGoods::getCategoryId).distinct().collect(Collectors.toList());

                    boolean flag = false;
                    for (int i = 0; i < cateIds.size(); i++) {
                        for (int j = 0; j < couponGoodsValue.length; j++) {
                            if (cateIds.get(i).equals(couponGoodsValue[j])) {
                                flag = true;
                            }
                        }
                    }

                    if (!flag) {
                        continue;
                    }
                } else if (goodType.equals(Constants.GOODS_TYPE_ARRAY)) {
                    Integer[] couponGoodsValue = couponStrategy.getSelectGoods();
                    boolean flag = false;
                    for (int i = 0; i < gsIds.size(); i++) {
                        for (int j = 0; j < couponGoodsValue.length; j++) {
                            if (gsIds.get(i).equals(couponGoodsValue[j])) {
                                flag = true;
                            }
                        }
                    }

                    if (!flag) {
                        continue;
                    }
                }
            }


            couponUserList.add(lumiereCouponUser);
        }
        return couponUserList;
    }


}
